package thread.lock;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @program: Multhread
 * @description: 独享锁
 * @author: zhanghz001
 * @create: 2021-03-04 20:48
 **/
public class ShareLock1 {
    public static void main(String[] args) {
        ShareLock1 lock = new ShareLock1();
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                lock.read();
            }).start();
        }
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                lock.write();
            }).start();
        }
    }
    
    ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    long start = System.currentTimeMillis();
    
    private void read() {
        ReentrantReadWriteLock.ReadLock readLock = readWriteLock.readLock();
        readLock.lock();
        try {
            Thread.sleep(100);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readLock.unlock();
        }
        long end = System.currentTimeMillis();
        
        System.out.println(end - start);
    }
    
    private void write() {
        ReentrantReadWriteLock.WriteLock writeLock = readWriteLock.writeLock();
        writeLock.lock();
        try {
            Thread.sleep(100);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            writeLock.unlock();
        }
        long end = System.currentTimeMillis();
        
        System.out.println(end - start);
    }
}
